package org.meow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.meow.constant.MsgConstant;
import org.meow.dto.UserLoginDTO;
import org.meow.dto.UserPageDTO;
import org.meow.dto.UserRegisterDTO;
import org.meow.entity.User;
import org.meow.exception.AccountNotFoundException;
import org.meow.exception.PasswordErrorException;
import org.meow.mapper.UserMapper;
import org.meow.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * &#064;Date: 24/05/14-13:46
 * &#064;Description:
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private UserMapper userMapper;

  @Override
  public User login(UserLoginDTO userLoginDTO) {
    String username = userLoginDTO.getUsername();
    String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", username);
    User user = userMapper.selectOne(queryWrapper);

    if (user == null)
      throw new AccountNotFoundException(MsgConstant.ACCOUNT_NOT_FOUND);
    if (!password.equals(user.getPasswd()))
      throw new PasswordErrorException(MsgConstant.PASSWORD_ERROR);
    return user;
  }

  @Override
  public void insert(UserRegisterDTO userRegisterDTO) {
    User user = new User();
    // BeanUtils.copyProperties(userRegisterDTO, user);
    // user.setUsername(userRegisterDTO.getUsername());
    // user.setPasswd(DigestUtils.md5DigestAsHex(userRegisterDTO.getPasswd().getBytes()));
    user.setCreateTime(LocalDateTime.now());
    userMapper.insert(user);
  }

  @Override
  public IPage<User> pageQuery(UserPageDTO userPageDTO) {
    IPage<User>        page         = new Page<>(userPageDTO.getCurr(), userPageDTO.getSize());
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id", "username", "email", "avatar", "create_time", "banned", "is_super");
    return userMapper.selectPage(page, queryWrapper);
  }

  @Override
  public void updateStatus(Integer status, Long id) {
    userMapper.update(null,
        Wrappers.<User>lambdaUpdate().eq(User::getId, id).set(User::getBanned, status == 0 ? 0 : 1));
  }

}
